package com.qf.flashlib.base;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ProgressBar;

import com.qf.flashlib.R;
import com.qf.flashlib.R2;
import com.qf.flashlib.exception.ApiException;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import butterknife.BindView;

/**
 * 装载WebView的fragment
 * 2018/9/14 10:58
 */
public class WebViewFragment extends LazyBaseFragment {

    @BindView(R2.id.pb_webview)
    ProgressBar mProgressBar;
    @BindView(R2.id.mWebView)
    WebView mWebView;
    private String mUrl;
    private static final String EXTRA_H5_URL = "EXTRA_H5_URL";

    /**
     * 入口方法
     */
    public static WebViewFragment initWebViewFragment(BaseActivity activity, @NonNull String url, boolean showProgress) {
        FragmentManager fragmentManager = activity.getSupportFragmentManager();
        FragmentTransaction fT = fragmentManager.beginTransaction();
        if (activity.getFragmentGroupId() == 0)
            throw new RuntimeException("Fragment parent id is not found...");
        WebViewFragment fragment = new WebViewFragment();
        Bundle bundle = new Bundle();
        bundle.putString(EXTRA_H5_URL, url);
        bundle.putBoolean("showProgress", showProgress);
        fragment.setArguments(bundle);
        fT.add(activity.getFragmentGroupId(), fragment);
        fT.commit();
        return fragment;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.stopLoading();
            mWebView.destroy();
            mWebView = null;
        }
    }

    /**
     * 构建WebSetting
     */
    @SuppressLint("SetJavaScriptEnabled")
    private void setWebSetting() {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);                         //支持JS
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);     //设置js可以直接打开窗口，如window.open()，默认为false
        webSettings.setDefaultTextEncodingName("utf-8");                //设置默认编码
        webSettings.setLoadsImagesAutomatically(true);                  //支持自动加载图片
        webSettings.setUseWideViewPort(true);                           //设置此属性，可任意比例缩放。大视图模式
        webSettings.setLoadWithOverviewMode(true);                      //和setUseWideViewPort(true)一起解决网页自适应问题
        webSettings.setAppCacheEnabled(true);                           //是否使用缓存
        webSettings.setDomStorageEnabled(true);                         //DOM Storage
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
    }

    /**
     * 构建webViewClient
     */
    WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            if (mWebView != null)
                mWebView.setVisibility(View.VISIBLE);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            view.setVisibility(View.GONE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    };

    /**
     * 构建webChromeClient
     */
    WebChromeClient webChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            Bundle arguments = getArguments();
            if (arguments == null)
                return;
            boolean showProgress = arguments.getBoolean("showProgress");
            if (mProgressBar == null || !showProgress)
                return;
            if (newProgress == 0) {
                mProgressBar.setVisibility(View.VISIBLE);
            }
            mProgressBar.setProgress(newProgress);
            if (newProgress == 100) {
                mProgressBar.setVisibility(View.GONE);
            }
        }
    };

    public Boolean onKeyDown(int keyCode) {
        //其中webView.canGoBack()在webView含有一个可后退的浏览记录时返回true
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (mWebView.canGoBack()) {
                mWebView.goBack();
                return true;
            } else {
                getActivity().finish();
            }
        }
        return true;
    }

    @Override
    protected int setContentView() {
        return R.layout.fragment_webview;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void lazyLoad() {
        initEventAndData();
    }

    public void initEventAndData() {
        //初始化WebView
        setWebSetting();
        mWebView.setWebChromeClient(webChromeClient);
        mWebView.setWebViewClient(webViewClient);
        //加载页面
        mUrl = getArguments() != null ? getArguments().getString(EXTRA_H5_URL) : "";
        if (!TextUtils.isEmpty(mUrl) && mUrl.startsWith("http"))
            mWebView.loadUrl(mUrl);
        else
            mWebView.loadDataWithBaseURL(null, getHtmlData(mUrl), "text/html", "utf-8", null);
    }

    private String getHtmlData(String bodyHTML) {
        bodyHTML = bodyHTML.replaceAll("\n", "<br>");
        String head = "<head>"
                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> "
                + "<style>img{max-width: 100%; width:100%; height:auto;}</style>"
                + "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }

    @Override
    public void onError(ApiException e) {

    }
}
